package com.ba.base.view.file

import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.ba.base.api.ApiFile
import com.ba.base.model.vo.UploadFileEntity
import com.ba.base.model.vo.UploadResult
import com.ypx.imagepicker.bean.ImageItem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import qsos.lib.base.callback.OnTListener
import qsos.lib.netservice.ApiEngine
import qsos.lib.netservice.expand.retrofit
import qsos.lib.netservice.file.UploadBody
import timber.log.Timber
import java.io.File
import kotlin.coroutines.CoroutineContext

/**
 * cx
 * @date : 2020/3/6
 * @description : 用于图片的上传
 */
class ImagePostHelper(
    val activity: AppCompatActivity,
    val mJob: CoroutineContext = Dispatchers.Main + Job()
) {
    private var mDialog: AlertDialog

    init {
        val mDialogBuilder = AlertDialog.Builder(activity)
        mDialogBuilder.setTitle("提示")
        mDialogBuilder.setMessage("提交中...请等待")
        mDialog = mDialogBuilder.create()
        mDialog.setCanceledOnTouchOutside(false)
        mDialog.setCancelable(false)
    }


    /**上传单张图片*/
    fun postImage(
        imageItem: ImageItem,
        success: OnTListener<List<UploadFileEntity>>,
        failed: OnTListener<String>
    ) {

        mDialog.show()
        val parts = arrayListOf<MultipartBody.Part>()
        val file: File = File(imageItem.path)
        val requestBody =
            RequestBody.create(MediaType.parse("multipart/form-data"), file)
        val uploadBody = UploadBody(requestBody, null)
        val part: MultipartBody.Part =
            MultipartBody.Part.createFormData("file", file.name, uploadBody)
        parts.add(part)

        CoroutineScope(mJob).retrofit<UploadResult> {
            api = ApiEngine.createService(ApiFile::class.java)
                .uploadFiles(url = ApiFile.UPLOAD_URL, files = parts)
            onSuccess {
                mDialog.dismiss()
                if (it == null) {
                    failed.back("文件上传失败，服务无数据")
                } else {
                    success.back(it.data)
                }
            }
            onFailed { _, _, e ->
                mDialog.dismiss()
                Timber.tag("文件上传").e(e)
                failed.back("文件上传失败 ${e.toString()}")
            }
        }
    }

}